<template>
  <div class="card">
    <div class="card-body">
      <div class="row">
        <div class="col-3 img-field">
          <img class="img-fluid" :src="user.photo">
        </div>
        <div class="col-9">
          <div class="username">{{ user.username }}</div>
          <div class="fans">粉丝：{{ user.followerCount }}</div>
          <button @click="follow" v-if="!user.is_followed" type="button" class="btn btn-secondary btn-sm">+关注</button>
          <button @click="unfollow" v-if="user.is_followed" type="button" class="btn btn-secondary btn-sm">取消关注</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import $ from 'jquery';
import { useStore } from 'vuex';
// @ is an alias to /src
export default {
  name: 'UserProfileInfo',
  props: { // 子组件接收父组件传递的数据
    user: {
      type: Object, // 数据类型
      required: true, // 必填
    },
  },
  setup(props,context) { 
    const store = useStore();
    const follow = () => { // 函数 关注
      $.ajax({
        url:"https://app165.acapp.acwing.com.cn/myspace/follow/",
        type:"POST",  
        headers:{
          "Authorization": "Bearer " + store.state.user.access,
        },
        data:{
          target_id:props.user.id,
        },
        success(resp){ 
          if(resp.result==="success"){
            context.emit('follow'); // 触发父组件的follow函数
          }     
        }
      })      
    }
    const unfollow = () => { // 函数 取消关注
      $.ajax({
        url:"https://app165.acapp.acwing.com.cn/myspace/follow/",
        type:"POST",  
        headers:{
          "Authorization": "Bearer " + store.state.user.access,
        },
        data:{
          target_id:props.user.id,
        },
        success(resp){ 
          if(resp.result==="success"){
            context.emit('unfollow'); // 触发父组件的follow函数
          }          
        }
      })
    }

    return {
      follow,
      unfollow,
    }
  }
}
</script>

<style scoped>
img {
  border-radius: 50%;
}
.username {
  font-size: 20px;
  font-weight: bold;
}
.fans {
  font-size: 14px;
}
.img-field {
  display: flex;
  flex-direction: column;
  justify-content: center; 
}
</style>